package oss

import (
	"bytes"
	"gitee.com/injoyai/goutil/oss/file"
	"image"
	"image/jpeg"
	"image/png"
	"os"
	"strings"
)

func OpenImage(path string) (image.Image, string, error) {
	file, err := os.Open(path)
	if err != nil {
		return nil, "", err
	}
	return image.Decode(file)
}

func OpenJpeg(path string) (image.Image, error) {
	file, err := os.Open(path)
	if err != nil {
		return nil, err
	}
	return jpeg.Decode(file)
}

func OpenPng(path string) (image.Image, error) {
	file, err := os.Open(path)
	if err != nil {
		return nil, err
	}
	return png.Decode(file)
}

func SaveImage(path string, img image.Image) error {
	switch strings.ToUpper(file.NewPath(path).NameSuffix()) {
	case "PNG":
		return SaveImagePng(path, img)
	case "JPG", "JPEG":
		return SaveImageJpeg(path, img)
	}
	return SaveImagePng(path, img)
}

func SaveImageJpeg(path string, img image.Image) error {
	bs := bytes.NewBuffer(nil)
	if err := jpeg.Encode(bs, img, nil); err != nil {
		return err
	}
	return file.New(path, bs)
}

func SaveImagePng(path string, img image.Image) error {
	bs := bytes.NewBuffer(nil)
	if err := png.Encode(bs, img); err != nil {
		return err
	}
	return file.New(path, bs)
}
